/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.backendbean;

import org.apache.http.HttpResponse;
import org.retabel.backendbean.lazylist.IOwLazyListLoader;
import org.retabel.backendbean.lazylist.OwLazyListFactory;
import org.retabel.jsf.RenderedDocumentUriBuilder;
import org.retabel.ui.RenderedDocumentPartUI;
import org.retabel.ui.RenderedDocumentUI;
import org.retabel.util.HttpGetClientRequestRunner;
import org.retabel.util.JaxbUtils;
import org.retabel.util.LogLines;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xsd.rendereddocument.RenderedDocument;
import xsd.rendereddocument.RenderedDocumentPart;
import xsd.rendereddocuments.RenderedDocuments;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Backend bean for paged enumeration of rendered documents
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 20:39 08.09.11
 *
 * @author Peter Herber
 * @version 1.0
 */
@ManagedBean
@RequestScoped
@Named
public class RenderedDocumentListBean2 {

    // constants

    private static final Logger log = LoggerFactory.getLogger(RenderedDocumentListBean2.class);

    // inner classes

    private class RenderedDocumentLazyList implements IOwLazyListLoader
    {
        @Override
        public List load(int pFirstEntryIndex, int pNumEntries) {
            try
            {
                List<RenderedDocumentUI> renderedDocumentUIs = new ArrayList<>();

                RenderedDocuments renderedDocuments = getPage(pFirstEntryIndex, pNumEntries);

                 for (RenderedDocument renderedDocument : renderedDocuments.getList().getRenderedDocument()) {
                    RenderedDocumentUI renderedDocumentUI = getRenderedDocumentUI(renderedDocument);

                    renderedDocumentUIs.add(renderedDocumentUI);
                }

                return renderedDocumentUIs;
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }
    }

    // private fields

    private LogLines logLines = new LogLines(log);

    private RenderedDocumentUI renderedDocument;

    // private functions

        /**
     * retrieve the page of rendered documents from retabel rest interface
     *
     * @param first   the first index
     * @param maxRows retrieve up to max rows
     * @return the rendered documents
     * @throws Exception if an error occurs
     */
    private RenderedDocuments getPage(int first, int maxRows) throws Exception {
        // we don't want any log lines, use null as log lines parameter therefore
        return new HttpGetClientRequestRunner<RenderedDocuments>(null) {
            @Override
            protected RenderedDocuments onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                return JaxbUtils.unmarshal(RenderedDocumentUriBuilder.getRenderedDocumentsXmlSchemaURI().toURL(),
                                           response.getEntity().getContent(), RenderedDocuments.class);
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "request failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(RenderedDocumentUriBuilder.getRenderedDocumentsURI(first, maxRows));
    }

    /**
     * converts a xml rendered document into a rendered document ui bean for display purposes
     *
     * @param renderedDocument the xml rendered document source
     * @return the converted rendered document ui bean
     */
    private RenderedDocumentUI getRenderedDocumentUI(RenderedDocument renderedDocument) throws URISyntaxException {
        RenderedDocumentUI renderedDocumentUI = new RenderedDocumentUI();

        renderedDocumentUI.setDocumentIdentifier(renderedDocument.getDocumentIdentifier());
        renderedDocumentUI.setCreated(renderedDocument.getCreated().toGregorianCalendar().getTime());

        if (renderedDocument.getList() != null && renderedDocument.getList().getRenderedDocumentPart() != null) {
            for (RenderedDocumentPart renderedDocumentPart : renderedDocument.getList().getRenderedDocumentPart()) {
                RenderedDocumentPartUI renderedDocumentPartUI = new RenderedDocumentPartUI();
                renderedDocumentPartUI.setId(renderedDocumentPart.getId());
                renderedDocumentPartUI.setMimeType(renderedDocumentPart.getMimeType());
                renderedDocumentPartUI.setFilename(renderedDocumentPart.getFilename());

                renderedDocumentPartUI.setUri(RenderedDocumentUriBuilder.getRenderedDocumentPartURI(
                    renderedDocument.getDocumentIdentifier(), renderedDocumentPart.getId()));

                renderedDocumentUI.getRenderedDocumentParts().add(renderedDocumentPartUI);
            }
        }
        return renderedDocumentUI;
    }

    // protected methods

    public List getList() throws Exception {
        RenderedDocuments renderedDocuments = getPage(1, 1);

        return OwLazyListFactory.createLazyList(new RenderedDocumentLazyList(), renderedDocuments.getCount(), 10);
    }

    // public functions

    public void delete() throws Exception {
    }

    public void showRenderedDocumentParts() throws Exception {
    }

    // beans

    /**
     * Gets the logLines.
     *
     * @return The logLines value.
     */
    public List<LogLines.LogLine> getAttributeLogLines() {
        return logLines.getLogLines();
    }

    /**
     * Gets the renderedDocument.
     *
     * @return The renderedDocument value.
     */
    public RenderedDocumentUI getRenderedDocument() {
        return renderedDocument;
    }
}